package api

import (
	"github.com/gin-gonic/gin"
	"zsc-boot/app/system_layer/model"
	"zsc-boot/core/orm"
	"zsc-boot/core/web"
)

type DictionaryApi struct {
}

func (d *DictionaryApi) Create(ctx *gin.Context) {
	var req model.Dictionary
	_ = ctx.Bind(&req)
	var oldData model.Dictionary
	if err := orm.GetDb().Where("`key` = ?", req.Key).Find(&oldData).Error; err != nil {
		web.FailResponse(ctx, err, "服务异常")
		return
	}

	if oldData.Key != "" {
		web.FailResponse(ctx, nil, "该配置已存在")
		return
	}

	if err := orm.GetDb().Create(&req).Error; err != nil {
		web.FailResponse(ctx, err, "服务异常")
		return
	}
	web.SuccessResponse(ctx, nil)
}

func (d *DictionaryApi) Delete(ctx *gin.Context) {
	var req model.Dictionary
	_ = ctx.Bind(&req)
	if err := orm.GetDb().Where("`key` = ?", req.Key).Delete(&req).Error; err != nil {
		web.FailResponse(ctx, err, "删除失败")
		return
	}
	web.SuccessResponse(ctx, nil)
}

func (d *DictionaryApi) List(ctx *gin.Context) {
	var res []model.Dictionary
	if err := orm.GetDb().Order("sort asc").Find(&res).Error; err != nil {
		web.FailResponse(ctx, err, "查询失败")
		return
	}
	web.SuccessResponse(ctx, res)
}

func (d *DictionaryApi) Update(ctx *gin.Context) {
	var req model.Dictionary
	_ = ctx.Bind(&req)
	if err := orm.GetDb().Where("`key` = ?", req.Key).Updates(&req).Error; err != nil {
		web.FailResponse(ctx, err, "删改失败")
		return
	}
	web.SuccessResponse(ctx, nil)
}

func (d *DictionaryApi) Detail(ctx *gin.Context) {
	key := ctx.Query("key")

	data := model.Dictionary{}
	if err := orm.GetDb().Where("`key` = ?", key).First(&data).Error; err != nil {
		web.FailResponse(ctx, err, "查询失败")
		return
	}
	web.SuccessResponse(ctx, data)
}
